package com.leemon.mall.security.controller;

import cn.hutool.captcha.AbstractCaptcha;
import com.leemon.mall.common.util.CacheManagerUtil;
import com.leemon.mall.security.constants.SecurityConstants;
import com.leemon.mall.security.service.SysLoginService;
import com.leemon.mall.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author limenglong
 * @create 2019-08-30 16:16
 * @desc 登录相关
 **/
@Api(tags = "后台-登录接口", description = "后台管理员登录、登出相关接口")
@RestController
public class SysLoginController {

    public static final Logger LOGGER = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @ApiOperation("获取验证码")
    @GetMapping("/captcha.jpg")
    public void generateCaptcha(
            @ApiParam(name = "uuid", value = "唯一标识") @RequestParam("uuid") String uuid,
            HttpServletResponse response) {

        AbstractCaptcha abstractCaptcha = sysLoginService.generateCaptcha(uuid);
        try {
            abstractCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            LOGGER.info("接口返回图片验证码失败,code:{}", abstractCaptcha.getCode(), e.getMessage());
            e.printStackTrace();
        }
    }

    @PostMapping(value = "/sys/logout")
    @ApiOperation("退出登录")
    public ResponseEntity logout(){
        //删除缓存
        cacheManagerUtil.evictCache(SecurityConstants.SECURITY_SYS_USER, SecurityUtils.getSysUser().getUsername());
        //清空上下文
        SecurityContextHolder.clearContext();
        return ResponseEntity.ok().build();
    }
}
